import React from "react";
import {connect} from "react-redux";
import request, {get, post_body} from "@/axios/tools";
import {Button, Form, Input, message, Table, Tabs} from "antd";

const {TabPane} = Tabs;
const {Item: FormItem} = Form;

class AddMember extends React.Component {
    constructor(props) {
        super(props)
    }

    restaurant = '';

    state = {
        data: [],
        showAdd: false,
        editId: '',
        editItem: {},
        phoneErrors: false,
    }
    columns = [
        {
            title: '会员编号',
            dataIndex: 'id',
            width: 160,
            render: text => <a>{text}</a>,
        },
        {
            title: '会员姓名',
            dataIndex: 'name',
            width: 200,
            render: (text, record, index) => {
                return this.state.editId === index ?
                    <Input defaultValue={text} onChange={(e) => {
                        this.editChange(e.target.value, record, 'name')
                    }}/>
                    : text;
            }
        },
        {
            title: '电话号码',
            dataIndex: 'phone',
            width: 200,
            render: (text, record, index) => {
                return this.state.editId === index ?
                    <div className={this.state.phoneErrors ? 'has-error' : ''} style={{position: 'relative'}}>
                        <Input defaultValue={text} onBlur={(e) => this.validValue(e.target.value, 'phone')}
                               onChange={(e) => {
                                   this.editChange(e.target.value, record, 'phone')
                               }}/>
                        {
                            this.state.phoneErrors ?
                                <span
                                    className="ant-form-explain"
                                    style={{position: 'absolute', left: 0, bottom: '-17px'}}>
                                 格式不正确
                            </span> : ''
                        }
                    </div>
                    : text;
            }
        },
        {
            title: '消费次数',
            dataIndex: 'costCount'
        },
        {
            title: '消费总额',
            dataIndex: 'costTotal'
        },
        {
            title: '操作',
            width: 160,
            render: (text, record, index) => (
                <div>
                    {
                        this.state.editId === index ?
                            (
                                <span>
                            <Button type="primary" onClick={this.updateMember}>
                                保存
                            </Button>
                            <span className="ant-divider"/>
                            <Button type="dashed" onClick={() => {
                                this.setState({editId: '', phoneErrors: false})
                            }}>
                                取消
                            </Button>
                        </span>
                            )
                            :
                            (
                                <span>
                            <Button className="plus-btn" type="dashed" onClick={() => {
                                this.setState({editId: index, editItem: {}})
                            }}>
                                编辑
                            </Button>
                                    {/*<span className="ant-divider"/>
                                     <Button type="dashed">
                                     删除
                                     </Button>*/}
                        </span>)
                    }


                </div>
            )
        }
    ];

    _requestMember = () => {
        // console.log(this.props)
        get('/restaurant/listMember/' + this.restaurant)
            .then((res) => {
                this.setState({data: res.list});
            }, (err) => {
                console.log(err);
            })
    }

    editChange = (val, record, key) => {
        const {editItem} = this.state;
        this.setState({
            editItem: {
                ...editItem,
                id: record.id,
                [key]: val
            }
        })
    }

    validValue = (val, key) => {
        let result = !(/^\d{11}$/g.test(val));
        this.setState({
            phoneErrors: result
        })
        return result
    };

    updateMember = () => {
        const {editItem, data} = this.state;
        if (JSON.stringify(editItem) === '{}') {
            this.setState({editId: ''})
            return
        }
        data.forEach((member) => {
            if (editItem.id === member.id) {
                ['name', 'phone'].forEach((field) => {
                    if (!editItem[field]) editItem[field] = member[field];
                })
            }
        })
        if (this.validValue(editItem.phone)) {
            return
        }
        editItem.restaurant = {id: this.restaurant}
        request({url: '/restaurant/member', method: 'post', body: editItem}).then((res) => {
            this._requestMember();
            message.success('修改成功');
            this.setState({editId: '', editItem: {}})
        }, (err) => {
            console.log(err)
            message.error('保存失败')
        });
    };

    handleSubmit = () => {
        const {form} = this.props;
        form.validateFields((errors, values) => {
            if (!errors && this.restaurant) {
                const values = form.getFieldsValue();
                request({
                    url: '/restaurant/member', method: 'post', body: {
                        ...values,
                        id: 0,
                        restaurant: {
                            id: this.restaurant
                        }
                    }
                }).then((res) => {
                    form.resetFields();
                    this._requestMember();
                    message.success('注册成功');
                }, (err) => {
                    console.log(err)
                });
            }
        })
    }

    componentDidMount() {
        const {auth: {data: {restaurant}}} = this.props;
        this.restaurant = restaurant
        this._requestMember();
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div className="content-container">
                <Tabs >
                    <TabPane tab="会员列表" key="1">
                        <div style={{padding: '10px 20px 20px 30px'}}>
                            <Table rowKey="id" columns={this.columns} dataSource={this.state.data}
                                   pagination={ false }/>
                        </div>
                    </TabPane>

                    <TabPane tab="会员注册" key="2">
                        <div style={{width: '600px', margin: '0 auto', padding: '20px 20px 0'}}>
                            <Form>
                                <FormItem
                                    label="电话号码"
                                    labelCol={{span: 4}}
                                    wrapperCol={{span: 18}}
                                >
                                    {getFieldDecorator('phone', {
                                        rules: [
                                            {required: true, message: '请输入电话号码'},
                                            {pattern: /^1[3456789]\d{9}$/g, message: '格式不正确'}
                                        ],
                                        validateTrigger: 'onBlur'
                                    })(
                                        <Input />
                                    )}
                                </FormItem>
                                <FormItem
                                    label="姓名"
                                    labelCol={{span: 4}}
                                    wrapperCol={{span: 18}}
                                >
                                    {getFieldDecorator('name', {
                                        rules: [{required: true, message: '请输入姓名'}],
                                    })(
                                        <Input />
                                    )}
                                </FormItem>
                                <FormItem
                                    wrapperCol={{span: 12, offset: 4}}
                                >
                                    <Button type="primary" onClick={this.handleSubmit}>提交</Button>
                                </FormItem>
                            </Form>
                        </div>
                    </TabPane>
                </Tabs>
            </div>
        )
    }
}

const mapStateToProps = state => {
    const {auth = {data: {}}} = state.httpData;
    return {auth};
};

export default connect(mapStateToProps)(Form.create()(AddMember));